package top.yzlin.dblock.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import top.yzlin.dblock.component.DatabaseInfo;

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Configuration
public class DatabaseConfig {
    private Environment environment;

    @Autowired
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Bean
    public Map<String, DatabaseInfo> databaseInfoMap(@Value("${jdbc-name}") String databaseName) {
        return Stream.of(databaseName.split(";"))
                .collect(Collectors.toMap(k -> k, this::createDatabaseInfo));
    }

    private DatabaseInfo createDatabaseInfo(String databaseName) {
        DatabaseInfo databaseInfo = new DatabaseInfo();
        BeanMap beanMap = BeanMap.create(databaseInfo);
        beanMap.forEach((o, v) -> beanMap.put(o, environment.getProperty("jdbc." + databaseName + "." + o, "")));
        return databaseInfo;
    }
}
